import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Announcement } from './announcement.entity';
import { FindOptionsWhere, In, Repository } from 'typeorm';
import { Annread } from './annread.entity';
import { DeptService } from 'src/dept/dept.service';
import { writeFileSync } from 'node:fs';
import { Http, NotFound } from 'src/util/http';
import { UserSys } from 'src/user/userSys.entity';

@Injectable()
export class AnnouncementService {
    constructor(
        @InjectRepository(Announcement)
        public readonly ann: Repository<Announcement>,
        @InjectRepository(Annread)
        public readonly annread: Repository<Annread>,
        private readonly deptService: DeptService
    ) { }

    async findBy(where: FindOptionsWhere<Announcement>) {
        return await this.ann.find({
            where,
            relations: ["author", "author.user", "depts", "system"],
            order: {
                id: "desc"
            }
        })
    }

    async save(entity: Announcement, {
        deptids,
        context,
        title
    }: any) {
        if (!entity) throw NotFound
        if (!context) throw Http.forbidden("内容不得为空")
        entity.depts = await this.deptService.dept.find({ where: { id: In(deptids) } })
        entity.title = title;
        const result = await this.ann.save(entity);
        writeFileSync(Announcement.getPath(result.id), context);
        return result;
    }

    async get(user: UserSys) {
        if (!user.system) return []
        const relations = ["author", "author.user"];
        const result = !user.dept ? [] : await this.ann.find({
            where: {
                depts: {
                    id: user.dept.id
                }
            },
            relations,
            order: { id: "desc" }
        })
        for (let i = 0; i < result.length; i++) {
            result[i].isRead = await this.annread.exist({
                where: {
                    user: {
                        id: user.id
                    },
                    ann: {
                        id: result[i].id
                    }
                }
            })
        }
        return result;
    }
}
